var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var isRefresh = false;
var api = frameElement.api, W = api.opener;
var callback = api.data.callback,oper = api.data.oper;
var ck_number = $("#ck_number").val();
var ba_number = $("#ba_number").val();
var from = $("#from").val();
var queryurl,querysumurl,querysizeurl,querysizetitleurl; 

if(from == "all"){//盘点批次的所有盘点
	var ba_isexec = $("#ba_isexec").val();
	queryurl = config.BASEPATH+'stock/check/check_detail_list_all/'+ba_number+'/'+ba_isexec;
	querysumurl = config.BASEPATH+'stock/check/check_detail_sum_all/'+ba_number+'/'+ba_isexec;
	querysizeurl = config.BASEPATH+'stock/check/check_detail_size_all/'+ba_number+'/'+ba_isexec;
	querysizetitleurl = config.BASEPATH+'stock/check/check_detail_size_title_all/'+ba_number+'/'+ba_isexec;
}else{//自己的盘点单据
	queryurl = config.BASEPATH+'stock/check/check_detail_list/'+ck_number;
	querysumurl = config.BASEPATH+'stock/check/check_detail_sum/'+ck_number;
	querysizeurl = config.BASEPATH+'stock/check/check_detail_size/'+ck_number;
	querysizetitleurl = config.BASEPATH+'stock/check/check_detail_size_title/'+ck_number;
}

var needListRefresh = false;//列表模式
var needSizeRefresh = false;//尺码模式
var needSumRefresh = false;//汇总模式
var _height = $(parent).height()-280,_width = $(parent).width()-2;

var showMode = {
	display:function(mode){
		var ids = $("#grid").getDataIDs();
		if(ids == undefined || null == ids || ids.length == 0){
			if(mode != 0){
				Public.tips({type: 1, content : "未添加数据，不能切换模式"});
				return;
			}
		}
		$("#CurrentMode").val(mode);
		$("a[name='mode-btn']").removeClass("on");
		$("#list-grid").hide();
		$("#size-grid").hide();
		$("#sum-grid").hide();
		if(mode == 0){
			$("#listBtn").addClass("on");
			$("#list-grid").show();
			showMode.refreshList();
		}else if(mode == 1){
			$("#sizeBtn").addClass("on");
			$("#size-grid").show();
			showMode.refreshSize();
		}else if(mode == 2){
			$("#sumBtn").addClass("on");
			$("#sum-grid").show();
			showMode.refreshSum();
		}
	},
	refreshList:function(){//列表模式刷新数据
		if(!needListRefresh){
    		return;
    	}
    	THISPAGE.reloadGridData();
    	needListRefresh = false;
	},
	refreshSum:function(){
		if(!needSumRefresh){
			return;
		}
		$('#sumGrid').GridUnload();
		THISPAGE.addEvent();
		THISPAGE.initSumGrid();
		needSumRefresh = false;
	},
	refreshSize:function(){
		if(!needSizeRefresh){
			return;
		}
		$.ajax({
			type:"POST",
			url:querysizetitleurl,
			cache:false,
			dataType:"json",
            success: function (data) {
            	if(undefined != data && data.stat == 200){
                    var titles = data.data.titles;
                    var sizeCodeMap = data.data.sizeCodeMap;
                    $('#sizeGrid').GridUnload();
                    THISPAGE.initSizeGroupGrid(titles, sizeCodeMap);
                    THISPAGE.addEvent();
                    needSizeRefresh = false;
				}else{
					Public.tips({type: 1, content : data.message});
				}
            }
        });
	},
	refresh:function(){
		var currentMode = $("#CurrentMode").val();
    	if(currentMode == '0'){//列表模式
    		needListRefresh = true;
    		showMode.refreshList();
        	needSizeRefresh = true;
        	needSumRefresh = true;
    	}else if(currentMode == '1'){//尺码模式
    		needSizeRefresh = true;
    		showMode.refreshSize();
    		needListRefresh = true;
        	needSumRefresh = true;
    	}else if(currentMode == '2'){//汇总模式
    		needSumRefresh = true;
    		showMode.refreshSum();
    		needListRefresh = true;
        	needSizeRefresh = true;
    	}
	}
};


var handle = {
	formatSubAmount :function(val, opt, row){
		return row.ckl_amount-row.ckl_stock_amount;
	},
	operFmatter :function(val, opt, row){
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-image" title="图片">&#xe654;</i>';
		html_con += '</div>';
		return html_con;
	}
};

var THISPAGE = {
	init:function (){
		this.initDom();
		this.addEvent();
		this.initGrid();
		this.initEvent();
	},
	initDom:function(){
		needListRefresh = false;//列表模式
        needSizeRefresh = true;//尺码模式
        needSumRefresh = true;//汇总模式
	},
	gridTotal:function(){
    	var grid=$('#grid');
		var ckl_amount=grid.getCol('ckl_amount',false,'sum');
		var ckl_stock_amount=grid.getCol('ckl_stock_amount',false,'sum');
    	var ckl_unitmoney=grid.getCol('ckl_unitmoney',false,'sum');
    	var ckl_retailmoney=grid.getCol('ckl_retailmoney',false,'sum');
    	grid.footerData('set',{pd_no:'合计：',ckl_amount:ckl_amount,ckl_stock_amount:ckl_stock_amount,sub_amount:'',ckl_unitmoney:ckl_unitmoney,ckl_retailmoney:ckl_retailmoney});
    	$("#ck_amount").val(ckl_amount);
    	$("#ck_stockamount").val(ckl_stock_amount);
    	$("#sub_amount").val(ckl_amount-ckl_stock_amount);
    },
    sumGridTotal:function(){
    	var grid=$('#sumGrid');
    	var ckl_amount=grid.getCol('ckl_amount',false,'sum');
    	var ckl_stock_amount=grid.getCol('ckl_stock_amount',false,'sum');
    	var ckl_unitmoney=grid.getCol('ckl_unitmoney',false,'sum');
    	var ckl_retailmoney=grid.getCol('ckl_retailmoney',false,'sum');
    	grid.footerData('set',{pd_no:'合计：',ckl_amount:ckl_amount,ckl_stock_amount:ckl_stock_amount,sub_amount:'',ckl_unitmoney:ckl_unitmoney,ckl_retailmoney:ckl_retailmoney});
    	$("#ck_amount").val(ckl_amount);
    	$("#ck_stockamount").val(ckl_stock_amount);
    	$("#sub_amount").val(ckl_amount-ckl_stock_amount);
    },
	initGrid:function(){
		var self=this;
		var colModel = [
		    {label:'操作',name:'operate', width: 40, fixed:true, formatter: handle.operFmatter, sortable:false,align:'center'},
		    {label:'',name: 'ckl_pd_code', index: 'ckl_pd_code', hidden:true},
	    	{label:'商品货号',name: 'pd_no', index: 'pd_no', width: 100},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 100},
	    	{label:'颜色',name: 'cr_name', index: 'cr_name', width: 60},
	    	{label:'尺码',name: 'sz_name', index: 'sz_name', width: 60},
	    	{label:'杯型',name: 'br_name', index: 'br_name', width: 60},
	    	{label:'单位',name: 'pd_unit', index: 'pd_unit', width: 60},
	    	{label:'库存数量',name: 'ckl_stock_amount', index: 'ckl_stock_amount', width: 70,align:'right',sorttype: 'int'},
	    	{label:'录入数量',name: 'ckl_amount', index: 'ckl_amount', width: 70,align:'right',sorttype: 'int',editable:true},
	    	{label:'相差数量',name: 'sub_amount', index: '', width: 70,align:'right',sortable:false,formatter: handle.formatSubAmount},
	    	{label:'零售价',name: 'ckl_retailprice', index: 'ckl_retailprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'零售金额',name: 'ckl_retailmoney', index: 'ckl_retailmoney', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'成本价',name: 'ckl_unitprice', index: 'ckl_unitprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'成本金额',name: 'ckl_unitmoney', index: 'ckl_unitmoney', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'备注',name: 'ckl_remark', index: 'ckl_remark', width: 180}
	    ];
		$('#grid').jqGrid({
			url:queryurl,
			loadonce:true,
			datatype: 'json',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
			multiselect:false,//多选
			viewrecords: true,
			rowNum:9999,//每页条数
			cmTemplate: {sortable:true,title:true},
			shrinkToFit:false,//表格是否自动填充
            footerrow: true,
			jsonReader: {
				root: 'data', 
				repeatitems : false,
				id: 'ckl_id'  //图标ID
			},
			loadComplete: function(data){
				var ids = $("#grid").getDataIDs();
				THISPAGE.gridTotal();
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	initSumGrid:function(){
		var self=this;
		var colModel = [
		    {label:'操作',name:'operate', width: 70, fixed:true, formatter: handle.operFmatter, sortable:false,align:'center'},
	    	{label:'',name: 'ckl_pd_code', index: 'ckl_pd_code', hidden:true},
	    	{label:'商品货号',name: 'pd_no', index: 'pd_no', width: 100},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 100},
	    	{label:'品牌',name: 'bd_name', index: 'pd_bd_code', width: 80},
	    	{label:'类别',name: 'tp_name', index: 'pd_tp_code', width: 80},
	    	{label:'单位',name: 'pd_unit', index: 'pd_unit', width: 60},
	    	{label:'库存数量',name: 'ckl_stock_amount', index: 'ckl_stock_amount', width: 70,align:'right',sorttype: 'int'},
	    	{label:'录入数量',name: 'ckl_amount', index: 'ckl_amount', width: 70,align:'right',sorttype: 'int'},
	    	{label:'相差数量',name: 'sub_amount', index: '', width: 70,align:'right',sortable:false,formatter: handle.formatSubAmount},
	    	{label:'零售价',name: 'ckl_retailprice', index: 'ckl_retailprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'零售金额',name: 'ckl_retailmoney', index: 'ckl_retailmoney', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'成本价',name: 'ckl_unitprice', index: 'ckl_unitprice', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'成本金额',name: 'ckl_unitmoney', index: 'ckl_unitmoney', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
	    	{label:'备注',name: 'ckl_remark', index: 'ckl_remark', width: 180}
	    ];
		$('#sumGrid').jqGrid({
			url:querysumurl,
			loadonce:true,
			datatype: 'json',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#sumPage',//分页
			pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
			multiselect:false,//多选
			viewrecords: true,
			rowNum:9999,//每页条数
			cmTemplate: {sortable:true,title:true},
			shrinkToFit:false,//表格是否自动填充
            footerrow: true,
			jsonReader: {
				root: 'data', 
				repeatitems : false,
				id: 'ckl_id'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.sumGridTotal();
			},
			loadError: function(xhr, status, error){		
			}
	    });
	},
	initSizeGroupGrid:function(dyColNames, sizeCodeMap) {
		var self=this;
		var gridWH = Public.setGrid();//操作
        var headers = [];
        var dyns = dyColNames;
        var dySize = dyns.length;
        var dms = [];
        for (var i = 0; i < dyns.length; i++) {
            var dys = dyns[i];
            for (var j = 0; j < dys.length; j++) {
                var dyss = null;
                dyss = dys[j].split('_AND_');
                if (i == 0 && j == 0) {
                    dyns[i][j] = dyss[0];
                }
                headers.push(dyss[1]);
                dms.push({label:dyss[1],name: dyss[0], index: dyss[0], width: 45, title: false, align: 'right', sorttype: 'int', sortable: false});
            }
            break;
        }
		var colModel = [
            {label:'',name: 'sizeGroupCode', hidden: true},
            {label:'',name: 'pd_code', index: 'pd_code', width: 100,hidden:true},
            {label:'',name: 'cr_code', index: 'cr_code', width: 100,hidden:true},
            {label:'',name: 'br_code', index: 'br_code', width: 100,hidden:true},
            {label:'操作',name:'operate', width: 70, fixed:true, formatter: handle.operFmatter, sortable:false,align:'center'},
            {label:'商品货号',name: 'pd_no', index: 'pd_no', width: 100},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 100},
	    	{label:'颜色',name: 'cr_name', index: 'ckl_cr_code', width: 60},
	    	{label:'杯型',name: 'br_name', index: 'ckl_br_code', width: 60},
        ];
        colModel = colModel.concat(dms);
        colModel = colModel.concat([
            {label:'数量',name: 'Amount_Total',	index:'Amount_Total',	width: 70, align: 'right', sorttype: 'int', sortable: false},
            {label:'零售价',name: 'retail_price', index: 'retail_price', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
	    	{label:'零售金额',name: 'retail_money', index: 'retail_money', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatBySell},
            {label:'成本价',name: 'unit_price', index: 'unit_price', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost},
            {label:'成本金额',name: 'unit_money', index: 'unit_money', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatByCost}
	    ]);
        $('#sizeGrid').jqGrid({
			url: querysizeurl,
			loadonce:true,
            datatype: 'json',
            autowidth: false,
            height: gridWH.h-100,
            gridview: true,
            colModel: colModel,
            rownumbers: true,//行号
            pager: '#sizePage',//分页
            pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
            viewrecords: true,
            rowNum: 9999,//每页条数
            shrinkToFit: false,//表格是否自动填充
            footerrow: true,
            userDataOnFooter: true,
			jsonReader: {
				root: 'data.data',
				userdata: 'data.userData',
				repeatitems : false,
				id:'id'
			},
			loadComplete: function(data) {
				
			},
			gridComplete:function(){
				Public.resizeSpecifyGrid('sizeGrid', 215 + (dyns.length * 32), 2);
			},
			loadError: function(xhr, status, error) {
                Public.tips({type: 1, content : '操作失败了哦，服务可能已过期，请按F5刷新！'});
			},
			onPaging: function(pgButton) {
				
			},
            onSelectRow: function (rowId, status) {
                var sizeG = $("#sizeGrid").jqGrid("getRowData", rowId).sizeGroupCode;
                var bg = $('[sizeGCode=' + sizeG + ']').css("background");
                if (bg == 'none') {
                    return;
                }
                $("[sizeGCode]").css("background-color", '#eee');
                $('[sizeGCode=' + sizeG + ']').css({ "background": "none", "background-color": "#F8FF94"});
            }
	    });
        if (dySize >= 2) {
        	$('#sizeGrid').jqGrid('setGroupHeaders', {
                useColSpanStyle: true,
                groupHeaders:[]
            });
            $('#sizeGrid').jqGrid("setComplexGroupHeaders", {
                complexGroupHeaders: {startColumnName: dyns[0][0], numberOfColumns: dyns[0].length},
                rowspan: dySize,
                topTitle:true
            });
            for (var key in sizeCodeMap) {
                $('#sizeGrid').jqGrid("setComplexGroupHeaders",{
                    complexGroupHeaders: {startColumnName: dyns[0][0], numberOfColumns: dyns[0].length},
                    rowspan: dySize,
                    sizeGroupCode: key,
                    titleTextGroup:sizeCodeMap[key],
                    topTitle:false
                });
            }
        }else{
        	$('#sizeGrid').jqGrid('setGroupHeaders', {
                useColSpanStyle: true,
                groupHeaders: [{startColumnName: dyns[0][0], numberOfColumns: dyns[0].length, titleText: '尺码'}]
            });
        }
    },
	reloadGridData: function () {
        $("#grid").jqGrid('setGridParam', {datatype: 'json', page: 1, url: queryurl}).trigger("reloadGrid");
    },
	initEvent:function(){
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
		$('#grid').on('click', '.operating .ui-icon-image', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
        	viewProductImg($("#grid").jqGrid("getRowData", id).ckl_pd_code);
        });
	},
	addEvent:function(){
		//移除事件，防止重复绑定
		$('#sumGrid').off('click','.operating .ui-icon-image');
		$('#sizeGrid').off('click','.operating .ui-icon-image');
		
		$('#sizeGrid').on('click', '.operating .ui-icon-image', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
        	viewProductImg($("#sizeGrid").jqGrid("getRowData", id).pd_code);
        });
        $('#sumGrid').on('click', '.operating .ui-icon-image', function (e) {
        	e.preventDefault();
        	var id = $(this).parent().data('id');
        	viewProductImg($("#sumGrid").jqGrid("getRowData", id).ckl_pd_code);
        });
	}
};

THISPAGE.init();